package cn.aifeix.basic.service.impl;

import cn.aifeix.basic.config.BussinessException;
import cn.aifeix.basic.constant.BaseConstant;
import cn.aifeix.basic.dto.EmailRegisterDto;
import cn.aifeix.basic.dto.PhoneRegisterDto;
import cn.aifeix.basic.service.IRegisterService;
import cn.aifeix.basic.util.MD5Utils;
import cn.aifeix.basic.util.StrUtils;
import cn.aifeix.user.domain.Logininfo;
import cn.aifeix.user.domain.User;
import cn.aifeix.user.mapper.LogininfoMapper;
import cn.aifeix.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void phoneRegister(PhoneRegisterDto dto) {
        // 调用参数校验方法
        this.verifyParam(dto);
        // 先插logininfo 再插user
        User user = dtoConvertUser(dto);
        Logininfo logininfo = userConvertLogininfo(user);
        // 设置类型为用户
        logininfo.setType(1);
        // 添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }


    @Override
    public void emailRegister(EmailRegisterDto dto) {
        // 调用参数校验方法
        this.verifyParam2(dto);
        // 先插logininfo 再插user
        User user = dtoConvertUser2(dto);
        Logininfo logininfo = userConvertLogininfo(user);
        // 设置类型为用户
        logininfo.setType(1);
        // 添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    /**
     * 将user属性赋给logininfo
     * @param user
     * @return
     */
    private Logininfo userConvertLogininfo(User user){
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        return logininfo;
    }

    /**
     * 手机注册将dto属性赋给user
     * @param dto
     * @return
     */
    private User dtoConvertUser(PhoneRegisterDto dto){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // md5加密密码
        String s = salt + dto.getPassword();
        String encryPwd = MD5Utils.encrypByMd5(s);
        return User
                .builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(encryPwd)
                .state(1)
                .createtime(new Date())
                .build();
    }
    /**
     * 邮箱注册将dto属性赋给user
     * @param dto
     * @return
     */
    private User dtoConvertUser2(EmailRegisterDto dto){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // md5加密密码
        String s = salt + dto.getPassword();
        String encryPwd = MD5Utils.encrypByMd5(s);
        // 随机生成一个用户名
        String username = StrUtils.getComplexRandomString(8);
        return User
                .builder()
                .username(username)
                .email(dto.getEmail())
                .salt(salt)
                .password(encryPwd)
                .state(1)
                .createtime(new Date())
                .build();
    }
    /**
     * 手机注册参数校验
     * @param dto
     */
    private void verifyParam(PhoneRegisterDto dto) {
        // 参数非空校验
        // 两次密码校验
        if (!dto.getPassword().equals(dto.getPasswordRepeat())){
            throw new BussinessException("两次密码不一致");
        }
        // 手机验证码是否正确、两次手机号是否一致
        // 取出redis中存的图形验证码
        String redisSmsCode = (String) redisTemplate.opsForValue().get(String.format(
                BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getPhone()));
        // 判断redis中验证码是否存在或者过期
        if (StringUtils.isBlank(redisSmsCode)){
            throw new BussinessException("验证码错误");
        }
        // 判断验证码是否正确
        String[] smsCode = redisSmsCode.split(":");
        if (!smsCode[0].equals(dto.getSmsCode())){
            throw new BussinessException("验证码错误！");
        }
        // 是否注册过
        User user = userMapper.findByPhone(dto.getPhone());
        if (null != user){
            throw new BussinessException("手机号已注册，请直接登录");
        }
    }
    /**
     * 邮箱注册参数校验
     * @param dto
     */
    private void verifyParam2(EmailRegisterDto dto) {
        // 参数非空校验
        // 两次密码校验
        if (!dto.getPassword().equals(dto.getPasswordRepeat())){
            throw new BussinessException("两次密码不一致");
        }
        // 邮箱验证码是否正确、邮箱手机号是否一致
        // 取出redis中存的图形验证码
        String redisEmailCode = (String) redisTemplate.opsForValue().get(String.format(
                BaseConstant.VerfityCodeCons.REGISTER_EMAILCODE_EMAIL, dto.getEmail()));
        // 判断redis中验证码是否存在或者过期
        if (StringUtils.isBlank(redisEmailCode)){
            throw new BussinessException("验证码错误");
        }
        // 判断验证码是否正确
        String[] emailCode = redisEmailCode.split(":");
        if (!emailCode[0].equals(dto.getEmailCode())){
            throw new BussinessException("验证码错误！");
        }
        // 是否注册过
        User user = userMapper.findByEmail(dto.getEmail());
        if (null != user){
            throw new BussinessException("邮箱已注册，请直接登录");
        }
    }

}
